<?php
/**
 * Cms_Expense
 *
 * @category   Cms
 * @package    Cms_Model
 */
class Cms_Model_Expense extends BIS_Model_Abstract
{
	
	/**
	 * Get all expenses
	 *
	 * @param array|null  $data  sort, order, page, limit, search
	 * @return Zend_Db_Table_Rowset|Zend_Paginator
	 */
	public function getExpenses($data=null)
	{
		if ($data) {
	
			$sortData = array('addedDate', 'expenseDate', 'description', 'amount');
	
			$order = '';
			if (isset($data['sort']) && in_array($data['sort'], $sortData)) {
				$order .= $data['sort'];
			} else {
				$order .= "addedDate";
			}
	
			if (isset($data['order']) && ($data['order'] == 'asc')) {
				$order .= " ASC";
			} else {
				$order .= " DESC";
			}
	
			$data['order'] = $order;
	
			if (isset($data['page'])) {
				if ($data['page'] < 0) {
					$data['page'] = 0;
				}
			}
	
			if (isset($data['limit'])) {
				if ($data['limit'] < 1) {
					$data['limit'] = 20;
				}
			}else{
				$data['limit'] = 20;
			}
	
			return $this->getResource('Expense')->getExpenses($data);
	
		} else {
			return $this->getResource('Expense')->getExpenses();
		}
	
	}
	
	/**
	 * Get expense by entry id
	 *
	 * @param  int $id The entry id
	 * @return Cms_Resource_Expense_Item|null
	 */
	public function getExpenseByEntryId($id)
	{
		$id = (int) $id;
	
		return $this->getResource('Expense')->getExpenseByEntryId($id);
	}
	
	/**
	 * Save a expense
	 *
	 * @param array  $data The data to insert/update
	 * @param string $savedBy The full name of the administrator that saved or updated the data
	 * @param Zend_DB_Table_Row $row Optional The row to use
	 * @return mixed The primary key
	 */
	public function saveExpense($data, $savedBy, $row = null)
	{
		$currentTime = date('Y-m-d H:i:s');
	
		// convert expenseDate to mysql data type
		if (array_key_exists('expenseDate', $data) && '' != $data['expenseDate']) {
			$mysqlDate = new Zend_Date($data['expenseDate'], 'dd.MM.yyyy');
			$data['expenseDate'] = $mysqlDate->toString('yyyy-MM-dd');
		}
	
		if(null !== $row){
			$data['lastUpdatedBy'] = $savedBy;
			$data['lastUpdatedDate'] = $currentTime;
		}else{
			$data['addedBy'] = $savedBy;
			$data['addedDate'] = $currentTime;
		}
	
		return $this->getResource('Expense')->saveRow($data, $row);
	}
	
	/**
	 * Delete a expense
	 *
	 * @param Zend_DB_Table_Row $row The row to use
	 * @return int The number of rows deleted
	 */
	public function deleteExpense($row)
	{
		return $this->getResource('Expense')->deleteRow($row);
	}
	
	/**
	 * Get expense report
	 *
	 * @param string|null   $fromDate	From expense date
	 * @param string|null   $toDate     To expense date
	 * @return Zend_Db_Table_Rowset
	 */
	public function getExpenseReport($fromDate=null, $toDate=null){
	
		return $this->getResource('Expense')->getExpenseReport($fromDate, $toDate);
	
	}
	
}